<template>
  <div class="import-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
      </el-card>
    </div>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel'
import { formatExcelDate } from '@/utils/index.js'
import { importEmployee } from '@/api/employees'

export default {
  components: { UploadExcelComponent },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    tranData(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      // return data.map(item => {
      //   let str = JSON.stringify(item)
      //   Object.keys(mapInfo).forEach(el => { str = str.replace(el, mapInfo[el]) })
      //   return JSON.parse(str)
      // })

      return data.map(item => {
        const obj = {}
        Object.keys(item).forEach(el => {
          if (el === '入职日期' || el === '转正日期') {
            obj[mapInfo[el]] = formatExcelDate(new Date(item[el]))
          } else {
            obj[mapInfo[el]] = item[el]
          }
        })
        return obj
      })
    },
    async handleSuccess({ results }) {
      console.log(results)
      const data = this.tranData(results)
      console.log(data)

      try {
        await importEmployee(data)
        this.$message.success('导入成功')
        this.$router.back()
      } catch (error) {
        this.$message.error(error.message)
      }
    }
  }
}
</script>
